//
//  UIImage+extension.swift
//  WeiboClassSix
//
//  Created by HM on 16/10/6.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit

extension UIImage {
    /// 返加一个纯色的图片
    ///
    /// - parameter size:  图片的大小
    /// - parameter color: 图片的颜色
    ///
    /// - returns: UIImage
    class func createImage(size: CGSize = CGSize(width: 1, height: 1), color: UIColor = UIColor.white) -> UIImage {
        //1. 开启上下文
        UIGraphicsBeginImageContext(size)
        
        //2. 设置填充颜色
        color.setFill()
        
        //3. 颜色填充
        let rect = CGRect(origin: CGPoint.zero, size: size)
        UIRectFill(rect)
        
        //4. 获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        //5. 关闭上下文
        UIGraphicsEndImageContext()
        
        return image!
    }
    
    
    /// 绘制圆形的图片
    ///
    /// - parameter size:  绘制的区间Rect
    /// - parameter color: 背景颜色
    func createCircleImage(size: CGSize = CGSize(width: 1, height: 1), color: UIColor = UIColor.white)-> UIImage {
        //1. 开启上下文
        UIGraphicsBeginImageContext(size)
        
        //2. 设置填充颜色
        color.setFill()
        
        //3. 颜色填充
        let rect = CGRect(origin: CGPoint.zero, size: size)
        UIRectFill(rect)
        
        //4. 添加裁切路径
        let path = UIBezierPath(ovalIn: rect)
        path.addClip()
        
        //5. 绘制
        self.draw(in: rect)
        
        //4. 获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        //5. 关闭上下文
        UIGraphicsEndImageContext()
        
        return image!
    }
    
    /// 异步绘制圆形的图片
    ///
    /// - parameter size:  绘制的区间Rect
    /// - parameter color: 背景颜色
    func createCircleImage(size: CGSize = CGSize(width: 1, height: 1), isCornered: Bool = true, color: UIColor = UIColor.white, callBack: @escaping (UIImage)->()){
        
        //在子线程中处理图片
        DispatchQueue.global().async {
            //1. 开启上下文
            UIGraphicsBeginImageContext(size)
            
            //2. 设置填充颜色
            color.setFill()
            
            //3. 颜色填充
            let rect = CGRect(origin: CGPoint.zero, size: size)
            UIRectFill(rect)
            
            if isCornered {
                //4. 添加裁切路径
                let path = UIBezierPath(ovalIn: rect)
                path.addClip()
            }

            //5. 绘制
            self.draw(in: rect)
            
            //4. 获取图片
            let image = UIGraphicsGetImageFromCurrentImageContext()
            
            //5. 关闭上下文
            UIGraphicsEndImageContext()
            
            DispatchQueue.main.async {
                callBack(image!)
            }
        }
    }
}











